import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CategoryEntity } from 'src/entity/category.entity';
import { CategoryDto } from 'src/modules/background/category/dto/category.dto';
import { CategoryReqDto } from 'src/modules/background/category/dto/category.req.dto';
import { CategoryListVo, CategoryVo } from 'src/modules/background/category/vo/category.vo';
import { getConnection, Repository } from 'typeorm';

@Injectable()
export class CategoryService {
    constructor(@InjectRepository(CategoryEntity) private readonly categoryRepository: Repository<CategoryEntity>) { }

    async add(data: CategoryDto): Promise<string> {
        try {

            const { name } = data
            if (name) {
                const result: Pick<CategoryEntity, 'id'> | undefined = await this.categoryRepository.findOne({ where: { name } })
                if (result) {
                    throw new HttpException(`${name}已存在请勿重复创建`, HttpStatus.OK)
                }  
                const category =  this.categoryRepository.create(data)
                await this.categoryRepository.save(category)
                return '创建成功'
            } 
            return ''
        } catch (error) {
            throw new HttpException(`创建失败`, HttpStatus.OK)
        }
    }

    // 删除
    async destoryCategoryById(id: number): Promise<string>{
        const result =  await this.categoryRepository.delete(id)
        if(result){
            return '删除成功'
        }else{
            return '删除失败'
        }
    }
    //查找
    async categoryList(): Promise<CategoryVo[]>{
        return await this.categoryRepository.find({select:['id','name']})
    }
    // 分页查找
    async categoryListPage(data: CategoryReqDto): Promise<CategoryListVo>{
        const {pageNum,pageSize} = data
        const [list, total] = await getConnection()
            .createQueryBuilder(CategoryEntity, 'category')
            .skip((pageNum - 1) * pageSize)
            .take(pageSize)
            .orderBy({ 'category.createdAt': 'DESC' })
            .printSql()
            .getManyAndCount();
            return {
                category:list,
                total,
                pageSize,
                pageNum
            }
    }
    // 更新
    async modifyCategoryById(id: number,data: CategoryDto): Promise<string>{
        const {
            raw: { affectedRows },
        } = await this.categoryRepository.update(id, data);
        if (affectedRows) {
            return '修改成功';
        } else {
            return '修改失败';
        }
    }
}
